#include "db.h"

Connection::Connection() {
    _conn = mysql_init(nullptr);
}

Connection::~Connection() {
    if (_conn != nullptr)
        mysql_close(_conn);
}

bool Connection::connect(const MySQLConfig& mysqlConfig) {
//    LOG_INFO<<"Connection::connect()";
    MYSQL *p = mysql_real_connect(_conn, mysqlConfig.ip.c_str(), mysqlConfig.user.c_str(),
                                  mysqlConfig.pwd.c_str(), mysqlConfig.dbName.c_str(), mysqlConfig.port, nullptr, 0);
    if (p != nullptr){
        //设置编码，可用中文
        mysql_query(_conn, "set names gbk");
    }else{
        LOG_ERROR << "Connection connection failed: " << mysql_error(_conn);
    }
    return p;
}

bool Connection::update(string sql) {
//    LOG_INFO<<"Connection::update: "<<sql;
    if (mysql_query(_conn, sql.c_str())){
        LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
                 << sql << "更新失败!";
        return false;
    }
    return true;
}

MYSQL_RES *Connection::query(string sql) {
//    LOG_INFO<<"Connection::query "<<sql;
    if (mysql_query(_conn, sql.c_str())){
        LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
                 << sql << "查询失败!";
        return nullptr;
    }
    return mysql_use_result(_conn);
}

MYSQL *Connection::getConn() const {
    return _conn;
}

void Connection::refreshAliveTime() {
    _aliveTime = clock();
}

clock_t Connection::getAliveTime() {
    return clock() - _aliveTime;
}
